<?php
    require_once(dirname(__FILE__)."/../include/main.php");
    require_once(dirname(__FILE__)."/../include/db.php");

    $db = connect();

    if (isset($_SESSION['game_id'])) {
        // ... Find the next Picture for this Game ...
    } else {
        
        // --- Choose a Random Picture
        //     This should always return a picture, but might actually take some time
        //     in the worst case.
        $pic = 0;
        $picId = 0;
        while (!$pic) {
            $picture_rows = $db->query(
                "SELECT t.picid FROM tags as t".
                (PIC_GROUP >= 0 ? ", pics as p WHERE t.picid = p.picid AND p.group = ".PIC_GROUP : "").
                " ORDER BY RAND() LIMIT 5"
            );
            if (!$picture_rows) die("Could not retrieve Picture from Database: ".$db->error);

            while ($picture_array = $picture_rows->fetch_array()) {
                if (!$picture_array['picid']) continue;
                $picId = $picture_array['picid'];
                $pic = PICS."/".$picId.".jpg";
                $hdr = @get_headers($pic);
                if ($hdr && $hdr[0] == "HTTP/1.1 200 OK") break;
                $pic = 0;
            }
        }
    }

    mysqli_close($db);

    //
    header('Content-Type: application/json');
    echo "{ \"id\": ".$picId.", \"url\": \"".$pic."\" }";
?>
